<?php
/**
 * @ClassName: Agent
 * @Description: 推客管理
 * @author: gydtrade
 * @Date: 2024-09-10 21:45
 * @Version: V1.0.0
 */

namespace app\admin\controller\agent;

use app\common\enum\CommonEnum;
use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Agent extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected $statistical_data = '';

    private string $msg;

    /**
     * 初始化
     **/
    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\Agent();
        $this->pageTitle = '推客管理';
        $this->pagesize = 10;

        $this->selectTextField = '{name}';
        $this->selectSearch = 'id|name|cust_id|contact_phone';

        // 列表页模型关联
        $this->indexWith = ['member'];
    }

    protected function buildDataList()
    {
        $page = input('post.__page__/d', 1);
        $page = $page < 1 ? 1 : $page;

        $where = $this->filterWhere();
        $table = $this->table;

        $pagesize = input('post.__pagesize__/d', 0);

        $this->pagesize = $pagesize ?: $this->pagesize;

        $total = $this->dataModel::where($where)->count();
        $data = $this->dataModel::where($where)
            ->with(['member'])
            ->order('create_time desc')
            ->limit(($page - 1) * $this->pagesize, $this->pagesize)
            ->select()->toArray();

        // 移除 status 条件
        /*$new_where = [];
        foreach ($where as &$item) {
            if ($item[0] != 'pay_status') {
                $new_where[] = $item;
            }
        }*/

        $total_amount = 0;
        $withdrawn = 0;
        $unwithdrawn = 0;
        $open_withdrawn = 0;
        $open_unwithdrawn = 0;
        $this->statistical_data = "总收入：{$total_amount}，已提现：{$withdrawn}，未提现：{$unwithdrawn}，开户奖已提现：{$open_withdrawn}，开户奖未提现：{$open_unwithdrawn}";

        $this->buildTable($data);
        $table->fill($data);
        $table->paginator($total, $this->pagesize);

        return $data;
    }

    /**
     * 构建搜索
     *
     * @return void
     **/
    protected function buildSearch()
    {
        $search = $this->search;
        $search->select('member_id', '会员')->dataUrl(url('/admin/member/selectPage'));
        $search->select('agent_level', '推客等级')->dataUrl(url('/admin/agent.agentlevel/selectPage'));
        $search->text('name', '推客名称');
        $search->text('contact_name', '推客联系人');
        $search->text('contact_phone', '推客联系电话');
        $search->text('cust_id', '第三方商户号');
        $search->select('status', '推客状态')->options(CommonEnum::examineText(true));
        $search->select('province', '省份')->dataUrl(url('api/areacity/province'), 'ext_name')->withNext(
            $search->select('city', '城市')->dataUrl(url('api/areacity/city'), 'ext_name')->withNext(
                $search->select('area', '地区')->dataUrl(url('api/areacity/area'), 'ext_name')
            )
        );
        $search->datetime('start', '时间')->placeholder('起始');
        $search->datetime('end', '~')->placeholder('截止');
    }

    /**
     * 构建搜索条件
     *
     * @return $where
     **/
    protected function filterWhere()
    {
        $searchData = request()->get();

        $where = [];
        if (!empty($searchData['member_id'])) {
            $where[] = ['member_id', 'eq', $searchData['member_id']];
        }
        if (!empty($searchData['agent_level'])) {
            $where[] = ['agent_level', 'eq', $searchData['agent_level']];
        }
        if (isset($searchData['name']) && $searchData['name'] != '') {
            $where[] = ['name', 'like', '%' . trim($searchData['name']) . '%'];
        }
        if (isset($searchData['contact_name']) && $searchData['contact_name'] != '') {
            $where[] = ['contact_name', 'like', '%' . trim($searchData['contact_name']) . '%'];
        }
        if (isset($searchData['contact_phone']) && $searchData['contact_phone'] != '') {
            $where[] = ['contact_phone', 'like', '%' . trim($searchData['contact_phone']) . '%'];
        }
        if (isset($searchData['cust_id']) && $searchData['cust_id'] != '') {
            $where[] = ['cust_id', 'like', '%' . trim($searchData['cust_id']) . '%'];
        }
        if (!empty($searchData['province'])) {
            $where[] = ['province', 'eq', $searchData['province']];
        }
        if (!empty($searchData['city'])) {
            $where[] = ['city', 'eq', $searchData['city']];
        }
        if (!empty($searchData['area'])) {
            $where[] = ['area', 'eq', $searchData['area']];
        }
        if (!empty($searchData['address'])) {
            $where[] = ['address', 'eq', '%' . $searchData['address'] . '%'];
        }
        if (!empty($searchData['status'])) {
            $where[] = ['status', 'eq', $searchData['status']];
        }
        if (!empty($searchData['start'])) {
            $where[] = ['create_time', 'egt', $searchData['start']];
        }
        if (!empty($searchData['end'])) {
            $where[] = ['create_time', 'elt', $searchData['end']];
        }

        return $where;
    }

    /**
     * 构建表格
     *
     * @return void
     **/
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        foreach ($data as &$d) {
            $d['__h_p__'] = !$d['status'] == 0;
        }

        $table->show('id', 'ID');
        $table->match('member_id', '关联会员')->to('{member.id}#{member.username}');
        $table->image('avatar', '头像')->thumbSize(40, 40);
        $table->show('name', '推客名称');
        $table->show('contact_name', '推客联系人');
        $table->show('contact_phone', '联系电话');
        $table->match('agent_level', '推客等级')->to('J{agent_level}');
        $table->match('attract_name', '招商等级');
        $table->show('operation_name', '运营等级');
        $table->show('cust_id', '第三方商户号')->default('--');
        $table->fields('real_info', '实名信息')->with(
            $table->show('realname', '真实姓名')->default('--'),
            $table->show('id_card_num', '身份证号')->default('--')
        );
        $table->match('agent_type', '推客类型')->options(model\Agent::$agent_type);
        $table->show('pcat', '展业地区');
        $table->show('total_amount', '总收入');
        $table->show('balance', '余额');
        $table->match('status', '状态')->options(CommonEnum::examineText(true))
            ->mapClassGroup([[-1, 'warning'], [0, 'info'], [1, 'success'], [2, 'danger']]);

        $table->fields('create_times', '申请/修改/审核时间')->with(
            $table->show('create_time', '添加时间'),
            $table->show('update_time', '修改时间'),
            $table->show('verify_time', '审核时间')
        )->getWrapper()->addStyle('width:160px');

        foreach ($data as &$d) {
            $d['__h_p__'] = $d['status'] != 0;
            $d['__h_unp__'] = $d['status'] != 0;
        }
        unset($d);

        $table->sortable('id, create_time');

        $table->addTop()->display($this->statistical_data)->addStyle("font-size:16px; font-weight: bold; color: #000;");

        $table->getToolbar()
            ->btnAdd()
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnView()
            ->btnPostRowid('pass', url('/admin/agent.agent/enable', ['state' => 1]), '通过', 'btn-success', '', '')
            ->btnPostRowid('unpass', url('/admin/agent.agent/enable', ['state' => 0]), '拒绝', 'btn-danger', '', '')
            ->mapClass([
                'pass' => ['hidden' => '__h_p__'],
                'unpass' => ['hidden' => '__h_unp__'],
            ]);
    }

    /**
     * 构建添加|编辑表单
     *
     * @param boolean $isEdit // 表单是否为编辑模式
     * @param array $data
     **/
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;

        $form->tab('基础信息');
        $form->select('member_id', '关联会员')->required()->dataUrl(url('/admin/member/selectpage'), '{nickname} | {mobile}');
        $form->image('avatar', '推客头像')->required();
        $form->text('name', '推客名称')->maxlength(100)->required();
        $form->text('contact_name', '推客联系人')->maxlength(50)->required();
        $form->text('contact_phone', '联系电话')->required()->maxlength(11);
        $form->text('cust_id', '第三方商户号');
        $form->select('attract_level', '招商等级')->dataUrl(url('/admin/agent.agentaward/selectAttractPage'));
        $form->select('agent_type', '推客类型')->options(model\Agent::$agent_type)->default(3)->required()
            ->when(1)->with(
                $form->fields('展业地区')->required(),
                $form->select('province', '省', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/province'), 'ext_name')->required(),
                $form->fieldsEnd()
            )->when(2)->with(
                $form->fields('展业地区')->required(),
                $form->select('province', '省', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/province'), 'ext_name')->required()->withNext(
                    $form->select('city', '市', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/city'), 'ext_name'))->required(),
                $form->fieldsEnd()
            )->when(3)->with(
                $form->fields('展业地区')->required(),
                $form->select('province', '省', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/province'), 'ext_name')->required()->withNext(
                    $form->select('city', '市', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/city'), 'ext_name')->required()->withNext(
                        $form->select('area', '区', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/area'), 'ext_name')->required()
                    )
                ),
                $form->fieldsEnd()
            );

        //提现限额
        $form->number('withdrawal_limit', '推客提现限额')->default(100)->required();

        $form->number('profit', '利润分配比例')->default(10)->required();
        $form->radio('status', '状态')->options([0 => '待审核', 1 => '通过', 2 => '不通过'])
            ->default(1)->required()->when(2,
                $form->textarea('remark', '备注')->required()
            );

        $form->tab('运营中心')->with(
            function () use ($form, $isEdit) {
                $form->defaultDisplayerSize(12, 12);
                $form->select('operation_level', '运营等级')->dataUrl(url('/admin/agent.agentaward/selectOperationPage'))->when(1)->with(
                    $form->select('operation_province', '省', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/province'))
                )->when(2)->with(
                    $form->select('operation_province', '省', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/province'), 'ext_name')->required()->withNext(
                        $form->select('operation_city', '市', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/city'), 'ext_name'))->required()
                )->when(3)->with(
                    $form->select('operation_province', '省', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/province'), 'ext_name')->required()->withNext(
                        $form->select('operation_city', '市', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/city'), 'ext_name')->required()->withNext(
                            $form->select('operation_area', '区', 4)->size(0, 12)->showLabel(false)->dataUrl(url('api/areacity/area'), 'ext_name')->required()
                        )
                    )
                );
            }
        );

        $form->tab('实名信息')->with(
            function () use ($form, $isEdit) {
                $form->fields('', '', 10)->size(0, 12)->showLabel(false)->with(
                    function () use ($form, $isEdit) {
                        $form->defaultDisplayerSize(12, 12);
                        $form->text('realname', '真实姓名');
                        $form->text('id_card_num', '身份证号码');
                        $form->image('idcard_front_photo', '身份证正面');
                        $form->image('idcard_back_photo', '身份证反面');
                        $form->image('hand_hold_idcard_photo', '手持身份证照');
                        $form->date('idcard_begin_date', '身份证有效期开始');
                        $form->radio('idcard_validity_type', '否长期有效')->options([0 => '短期', 1 => '长期'])->default(0)->when(0)->with(
                            $form->date('idcard_end_date', '身份证有效期截止')
                        );
                    }
                );
            }
        );

        $form->tab('结算信息')->with(
            function () use ($form, $isEdit) {
                $form->defaultDisplayerSize(12, 12);
                $form->text('settle_name', '结算人姓名');
                $form->text('bank_card_no', '结算账户');
                $form->text('bank_cell_phone', '银行预留手机号');
                $form->image('bank_card_photo', '结算卡照片');
                $form->text('bank_shot_name', '银行简称');
                $form->text('bank_full_name', '结算银行全称');
                $form->text('bank_branch_name', '结算银行支行名称');
                $form->text('unionpay_code', '联行号');
                $form->select('bank_province', '开户省份', 4)->dataUrl(url('api/areacity/province'), 'ext_name')->withNext(
                    $form->select('bank_city', '开户城市', 4)->dataUrl(url('api/areacity/city'), 'ext_name')->withNext(
                        $form->select('bank_area', '开户地区', 4)->dataUrl(url('api/areacity/area'), 'ext_name')
                    )
                );
                $form->text('bank_area_str', '开户行地区');
            }
        );
    }

    /**
     * 整体添加|修改
     * @param $id
     * @return \think\response\Json|\tpext\think\View
     */
    private function save($id = 0)
    {
        $data = request()->post();

        $result = $this->validate($data, [
            'name|推客名称' => 'require',
            'profit' => 'number|between:0,100',
            'member_id|推客关联会员' => 'require|number',
        ], [
            'profit.number' => '分成比例只能是数字',
            'profit.between' => '分成比例只能是0-100之间的数字',
        ]);

        if (true !== $result) {
            $this->error($result);
        }

        if ($data['id_card_num']) {
            $agent = $this->dataModel->where('id_card_num', $data['id_card_num'])->find();
            if ($agent) {
                $this->error('一个身份证只能绑定一个推客身份');
            }
        }

        //判断推客区域是否唯一
        /*if ($id) {
            $agent = model\Agent::where('id', $id)->find();
            if ($data['agent_type'] == 1) {
                //市代理
                if ($agent['city'] != $data['city']) {
                    $region = model\Agent::where('city', $data['city'])->find();
                    if ($region) {
                        $this->error('该城市已有推客');
                    }
                }
            } elseif ($data['agent_type'] == 2) {
                //区县代理
                if ($agent['area'] != $data['area']) {
                    $region = model\Agent::where('area', $data['area'])->find();
                    if ($region) {
                        $this->error('该区县已有推客');
                    }
                }
            } else {
                //省代理
                if ($agent['province'] != $data['province']) {
                    $region = model\Agent::where('province', $data['province'])->find();
                    if ($region) {
                        $this->error('该省已有推客');
                    }
                }
            }
        } else {
            if ($data['agent_type'] == 1) {
                //市代理
                $region = model\Agent::where('city', $data['city'])->find();
                if ($region) {
                    $this->error('该城市已有推客');
                }
            } elseif ($data['agent_type'] == 2) {
                //区县代理
                $region = model\Agent::where('area', $data['area'])->find();
                if ($region) {
                    $this->error('该区县已有推客');
                }
            } else {
                //省代理
                $region = model\Agent::where('province', $data['province'])->find();
                if ($region) {
                    $this->error('该省已有推客');
                }
            }
        }*/

        unset($data['__token__']);

        if ($id) {
            $data['update_time'] = date_now();
            $old_member_id = $this->dataModel->where('id', '=', $id)->value('member_id');
            if ($old_member_id != $data['member_id']) {
                // 当后台修改代理绑定会员时
                $agent = model\Agent::where('member_id', '=', $data['member_id'])->find();
                if (!$agent) {
                    $this->error('该用户已有关联推客');
                }
            }

            $res = $this->dataModel->where('id', $id)->update($data);

            if (!$res) {
                return $this->builder()->layer()->closeRefresh(0, '推客信息更新失败');
            }
        } else {
            $data['create_time'] = $data['update_time'] = date_now();//创建/审核时间

            $agent = model\Agent::where('member_id', '=', $data['member_id'])->find();
            if (!$agent) {
                $this->error('该用户已有关联推客');
            }

            if ($data['status'] == CommonEnum::check_success) {
                $data['verify_time'] = date_now();//审核时间
            }

            $agent_id = model\Agent::insertGetId($data);

            if (!$agent_id) {
                $this->error('推客信息新增成功');
            }
        }

        return $this->builder()->layer()->closeRefresh(1, __blang('bilder_save_succeeded'));
    }

    /**
     * 审核:通过
     * @return void
     */
    public function pass()
    {
        $ids = input('post.ids', '');
        $ids = array_filter(explode(',', $ids), 'strlen');
        if (empty($ids)) {
            $this->error('参数有误');
        }
        $res = 0;
        foreach ($ids as $id) {
            if ($this->trans($id)) {
                $res += 1;
            }
        }
        if ($res) {
            $this->success('成功操作' . $res . '条数据');
        } else {
            $this->error('操作失败' . $this->msg);
        }
    }

    /**
     * 审核:不通过
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function unpass()
    {
        $ids = input('post.ids', '');
        $ids = array_filter(explode(',', $ids), 'strlen');
        if (empty($ids)) {
            $this->error('参数有误');
        }
        $res = 0;
        foreach ($ids as $id) {
            if ($this->trans($id, '不通过')) {
                $res += 1;
            }
        }
        if ($res) {
            $this->success('成功操作' . $res . '条数据');
        } else {
            $this->error('操作失败' . $this->msg);
        }
    }

    /**
     * 批量审核操作
     * @param $id
     * @param $remark
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function trans($id, $remark = '通过申请')
    {
        $agent = $this->dataModel->where(['id' => $id])->find();

        if (!$agent) {
            $this->msg = '推客不存在';
            return false;
        }
        if ($agent['status'] != 0) {
            $this->msg = '状态不是待审核状态';
            return false;
        }

        //更新代理状态
        $res = $this->dataModel->where(['id' => $id])
            ->update([
                'status' => CommonEnum::check_success,
                'remark' => $remark,
                'update_time' => date('Y-m-d H:i:s'),
                'verify_time' => date_now()
            ]);

        return $res;
    }

}